package com.leetcode;

import java.util.HashSet;
import java.util.Set;

/**
 * 804. 唯一摩尔斯密码词
 */
public class Solution804 {

    private final static String[] MORSE = new String[]{".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--.."};

    /**
     * 性能优化版
     *
     * @param words
     * @return
     */
    public int uniqueMorseRepresentations(String[] words) {
        if (words == null || words.length == 0) {
            return 0;
        }
        Set<String> codesSet = new HashSet<>(words.length);
        for (String word : words) {
            StringBuilder code = new StringBuilder();
            for (char ch : word.toCharArray()) {
                code.append(MORSE[ch - 'a']);
            }
            codesSet.add(code.toString());
        }
        return codesSet.size();
    }

    public int uniqueMorseRepresentations1(String[] words) {
        if (words == null || words.length == 0) {
            return 0;
        }
        String[] codes = new String[]{".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--.."};
        Set<String> set = new HashSet<>(words.length);
        for (String word : words) {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < word.length(); i++) {
                String code = codes[word.charAt(i) - 'a'];
                sb.append(code);
            }
            set.add(sb.toString());
        }
        return set.size();
    }

    public static void main(String[] args) {
        String[] words = new String[]{"gin", "zen", "gig", "msg"};
        int res = new Solution804().uniqueMorseRepresentations(words);
        System.out.println(res);
    }

}
